package com.ruoyi;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.ArrayList;
import java.util.List;

public class UdpReceiver {

    // 声明事件和监听器接口
    public interface DataReceivedListener {
        void onDataReceived(String data);
    }
    private DatagramSocket udpSocket;
    private int port;
    private ConcurrentLinkedQueue<String> dataQueue;
    private List<DataReceivedListener> dataReceivedListeners;

    public UdpReceiver(int port) {
        this.port = port;
        this.dataQueue = new ConcurrentLinkedQueue<>();
        this.dataReceivedListeners = new ArrayList<>();
    }

    public void start() {
        try {
            udpSocket = new DatagramSocket(port);

            // 启动后台线程处理缓冲队列中的数据
            new Thread(this::processDataQueueInBackground).start();

            // 开始接收UDP数据包
            receiveData();
        } catch (Exception ex) {
            System.err.println("启动UDP接收端出错：" + ex.getMessage());
        }
    }

    private void receiveData() {
        try {
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            while (true) {
                udpSocket.receive(packet);
                String receivedData = new String(packet.getData(), 0, packet.getLength());
                dataQueue.add(receivedData);
                //<<<<<<<<<<<<<<<<<<<<
                InetAddress address = packet.getAddress();
                int portNumber = packet.getPort();
                String response = "Success Received ！"; // 反馈信息
                System.out.println("接收UDP数据来源地址：" + address.toString()+":"+portNumber);
                // 将反馈信息发送回客户端
                DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, address, portNumber);
                udpSocket.send(responsePacket);
            }
        } catch (Exception ex) {
            System.err.println("接收UDP数据出错：" + ex.getMessage());
        }
    }

    private void processDataQueueInBackground() {
        while (true) {
            if (!dataQueue.isEmpty()) {
                String data = dataQueue.poll();
                onDataReceived(data);
            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 添加多个监听者
    public void addDataReceivedListener(DataReceivedListener listener) {
        dataReceivedListeners.add(listener);
    }

    // 解除监听者
    public void removeDataReceivedListener(DataReceivedListener listener) {
        dataReceivedListeners.remove(listener);
    }

    private void onDataReceived(String data) {
        for (DataReceivedListener listener : dataReceivedListeners) {
            listener.onDataReceived(data);
        }
    }

    // 停止UDP接收端
    public void stop() {
        if (udpSocket != null) {
            udpSocket.close();
        }
    }

}
